import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { Button, message, Input } from 'antd';
import { getPayOrder, queryRule } from './service';

import OrderCommon from '@/pages/OrderCommon';
import CreateForm from './components/CreateForm';
import { money_trans } from '@/utils/utils';

const TableList = (props) => {
  const [payOrderValues, setPayOrderValues] = useState({});
  const [order, setOrder] = useState(false);
  const [uploadLoading, setUploadLoading] = useState(false);
  const [memberNumber, setMemberNumber] = useState();
  const [count, setCount] = useState();
  const actionRef = useRef();
  const handlePay = (params) => {
    getPayOrder(params).then((res) => {
      const { code, data } = res;
      code === 0 ? (setPayOrderValues(data), setOrder(true)) : null;
    });
  };
  const uploadOnChange = (info) => {
    setUploadLoading(true);
    if (info.file.status === 'done') {
      setUploadLoading(false);
      const {
        file: {
          response: { code },
        },
      } = info;
      if (code == 0) {
        actionRef.current.reload();
        message.success('导入成功');
      } else {
        message.error('导入失败请重试！');
      }
    } else {
      // message.error('导入失败请重试！');
    }
  };
  useEffect(() => {
    const { query } = props.history.location;
    query?.cardNum ? setMemberNumber(query?.cardNum) : null;
    actionRef.current.reload();
  }, [props.history.location.query?.cardNum]);
  const columns = [
    {
      title: '单据号',
      dataIndex: 'number',
      valueType: 'text',
    },
    {
      title: '会员名称',
      dataIndex: 'memberName',
      render: (dom, entity) => {
        return <a>{dom}</a>;
      },
    },
    {
      title: '会员卡号',
      dataIndex: 'memberNumber',
      renderFormItem: () => {
        return (
          <Input
            allowClear
            onChange={(e) => setMemberNumber(e.target.value)}
          />
        );
      },
    },

    {
      title: '店铺名称',
      dataIndex: 'storeName',
    },

    {
      title: '实付金额',
      dataIndex: 'amount',
      valueType: 'text',
      hideInSearch: true,
      render: (dom, entity) => {
        return money_trans(dom, true);
      },
    },
    {
      title: '获得积分',
      dataIndex: 'integral',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '是否赠送',
      dataIndex: 'isGift',
      valueEnum: {
        true: {
          text: '是',
          status: 'Success',
        },
        false: {
          text: '否',
          status: 'Error',
        },
      },
    },
    {
      title: '消费时间',
      dataIndex: 'createTime',
      hideInSearch: true,
      render: (dom) => {
        return <div>{new Date(dom).toLocaleString()}</div>;
      },
    },
    {
      title: '消费时间',
      dataIndex: 'created_at',
      hideInTable: true,
      valueType: 'dateRange',
      search: {
        transform: (value) => {
          return {
            startCreateTime: value[0],
            endCreateTime: value[1],
          };
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      hideInSearch: true,
      valueType: 'text',
      render: (_, record) => {
        return (
          <a
            onClick={() => {
              handlePay(record.billId);
            }}
          >
            查看单据
          </a>
        );
      },
    },
  ];
  return (
    <PageContainer>
      <ProTable
        headerTitle="消费记录"
        actionRef={actionRef}
        rowKey="id"
        scroll={{ x: 1200 }}
        bordered
        search={{
          labelWidth: 120,
        }}
        footer={(record) => {
          let num =
            record.length > 0
              ? record.reduce((c, item) => {
                  return c + Number(item.amount);
                }, 0)
              : 0;
          return (
            <div>
              <span>消费金额合计：</span>
              <a>{Number(num).toFixed(2)}</a>
            </div>
          );
        }}
        // toolBarRender={() => {
        //   return [
        //     <Upload
        //       name="file"
        //       action={() => {
        //         return `${defaultSetting.baseUrl}pay/order/excel/consume`;
        //       }}
        //       listType="picture"
        //       showUploadList={false}
        //       maxCount={1}
        //       onChange={uploadOnChange}
        //       headers={{ token: sessionStorage.getItem('token'), type: 'ADMIN' }}
        //     >
        //       <Button type="primary" loading={uploadLoading} icon={<UploadOutlined />}>
        //         导入一卡易交易数据
        //       </Button>
        //     </Upload>,
        //   ];
        // }}
        toolBarRender={() => {
          const { query } = props.history.location;
          return query.cardNum ? (
            <Button
              type="primary"
              onClick={() => {
                props.history.goBack();
              }}
            >
              返回
            </Button>
          ) : (
            false
          );
        }}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter, memberNumber:memberNumber })}
        onReset={(params) => {
          props.history.replace(
            { cardNum: '' },
            props.history.location,
          );
          setMemberNumber()
          actionRef.current.reload();
        }}
        postData={(payload) => {
          const { list, total } = payload;
          setCount(total);
          message.success(`${props.history.location.query.cardNum||''}消费记录查询成功!`)
          return list;
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        columns={columns}
      />
      <CreateForm width={1200} onCancel={() => setOrder(false)} modalVisible={order}>
        <OrderCommon payOrderValues={payOrderValues} />
      </CreateForm>
    </PageContainer>
  );
};

export default TableList;
